'''
1表示 可以，0表示不行
_____________________________________________
模式      r     r+      w      w+     a    a+
读        1     1       0      1      0    1
写        0     1       1      1      1    1
创建      0     0       1      1      1    1
覆盖      0     0       1      1      0    0
指针在头  1     1       1      1      0    0
指针在尾  0     0       0      0      1    1 
_____________________________________________
'''
import uos
import utime as time

class SetTfCard():
    def __init__(self,rtcobj):
        self.header = []
        self.filename = None
        self.myrtc = rtcobj
        self.ddate = None
        self.is_head_init = False  # 用于跟踪是否已初始化表头
        self.is_sd_init = False   # TF卡是否挂载

        self.retry_count = 0      # 重试计数器
        self.max_retries = 3      # 最大重试次数
        self.last_check_time = 0  # 上次检查时间
        self.check_interval = 5   # 检查间隔（秒）

        self.mount_sd_card()

    def mount_sd_card(self):
        '''
         brief:挂载函数，检查是否SD卡挂载,增加重试机制
        '''
        try:
            if uos.mountsd(): 
                print('SD Card is mounted ')
                self.is_sd_init = True
                self.retry_count = 0  # 重置重试计数
                return True
            else:
                print('SD Card mount point do not exist')
                self.is_sd_init = False
                return False
        except Exception as e:
            print('SD Card mount error: {}'.format(e))
            self.is_sd_init = False
            return False

    def check_sd_card_status(self):
        """
        brief:检查SD卡状态，增加智能重试和时间间隔控制
        """
        current_time = time.time()
        # 如果距离上次检查时间不足间隔时间，且SD卡状态正常，则跳过检查
        if (current_time - self.last_check_time < self.check_interval
            and self.is_sd_init):
            return self.is_sd_init
        self.last_check_time = current_time
        # 检查SD卡是否仍然可用
        if self.is_sd_init:
            try:
                # 尝试访问SD卡目录来验证是否仍然挂载
                uos.listdir('/sdcard0')
                return True
            except:
                print('SD Card disconnected, attempting remount...')
                self.is_sd_init = False
                self.is_head_init = False  # 重置表头标志
        
        # 如果SD卡未挂载或检测到断开，尝试重新挂载
        if not self.is_sd_init and self.retry_count < self.max_retries:
            self.retry_count += 1
            # 添加延迟，给SD卡一些时间稳定
            time.sleep(1)
            if self.mount_sd_card():
                print('SD Card remounted successfully')
                return True
            else:
                print('SD Card remount failed attempt:',self.retry_count)
        elif self.retry_count >= self.max_retries:
            print('Max retry attempts reached. Please check SD card connection.')
        return self.is_sd_init
    def unmount_sd_card(self):
        """
        brief:安全卸载SD卡
        """
        try:
            if self.is_sd_init:
                # 这里可以添加卸载逻辑，如果uos支持的话
                uos.umountsd()  # 假设存在此方法
                self.is_sd_init = False
                self.is_head_init = False
                print('SD Card unmounted safely')
                return True
        except Exception as e:
            print('Error unmounting SD card:',e)
        return False

    def wirte_to_name(self,head):
        '''
        brief:存储文件表头
        args: head 字符串
        '''
        try:
            self.ddata = self.myrtc.getRtcTime()
            # print(self.ddata)
            self.ddata = self.ddata.replace(' ','-').replace(':','-')
            frontstr = '/sdcard0/'
            endstr = '.csv'
            self.filename = frontstr +self.ddata + endstr
            print("filename:",self.filename)
            #写入表头
            with open(self.filename,'w') as f:
                if not self.header:
                    self.header.append('Time')
                    for para in head:
                        self.header.append(para)
                    f.write(','.join(self.header)+'\n')
                    
                return True
        except Exception as e:
            print("Error creating file header: ",e)
            self.is_sd_init = False
            return False

    def wirte_to_csv(self, head, *data):
        '''
        brief: 将数据写入csv文件，增强热拔插处理能力
        data: 要写入的数据,类型为列表
        head:字符串
        '''
        # 检查SD卡状态
        if not self.check_sd_card_status():
            print('SD Card is not available, data not saved')
            return False
            
        # 如果表头未初始化或文件不存在，重新创建
        if not self.is_head_init or not self._file_exists():
            if not self.wirte_to_name(head):
                return False
            self.is_head_init = True
        ddata = self.myrtc.getRtcTime()
        row_data = [ddata] + (list(data))[0]
        try:
            with open(self.filename, 'a') as f:
                f.write(','.join(map(str, row_data)) + '\n')
                
            return True
        except OSError as e:
            print("SD Card write error (possibly disconnected):",e)
            self.is_sd_init = False
            self.is_head_init = False
            return False
        except Exception as e:
            print("Unexpected error writing to file:",e)
            return False


    def _file_exists(self):
        """
        brief:检查文件是否存在
        """
        if not self.filename:
            return False
        try:
            with open(self.filename, 'r'):
                pass
            return True
        except:
            return False
    
    def get_sd_status(self):
        """
        brief:获取SD卡当前状态信息
        return: dict 包含状态信息的字典
        """
        return {
            'is_mounted': self.is_sd_init,
            'retry_count': self.retry_count,
            'max_retries': self.max_retries,
            'current_file': self.filename,
            'header_initialized': self.is_head_init
        }
    
      
           
            




    


 

